package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.mp.model.OauthToken;
import com.foxinmy.weixin4j.payment.PayRequest;
import com.foxinmy.weixin4j.type.TradeType;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.exception.YgHttpException;
import com.ygqh.baby.handler.CommitOrderHandler;
import com.ygqh.baby.handler.ShoppingCarHandler;
import com.ygqh.baby.model.*;
import com.ygqh.baby.observer.Observable.OrderPaySuccessObservable;
import com.ygqh.baby.observer.OrderPayModel;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserAddress;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.service.trustone.YgCustomsApi;
import com.ygqh.baby.service.trustone.model.ApiResult;
import com.ygqh.baby.service.wechat.YgWeChatService;
import com.ygqh.baby.service.wechat.protocol.UnifiedOrderReqData;
import com.ygqh.baby.utils.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 订单
 *
 * @author guohao
 */
@Controller
@RequestMapping("/mobile/order")
public class YgOrderController extends BaseController {

    @Autowired
    private YgShoppingCarService shoppingCarService;
    @Autowired
    private YgOrderService orderService;
    @Autowired
    private YgUserService userService;
    @Autowired
    private YgOrderPaymentService orderPaymentService;
    @Autowired
    private WxMpAuthorityService wxMpAuthorityService;
    @Autowired
    private YgFrameCodeService ygFrameCodeService;
    @Autowired
    private DocumentConstant documentConstant;
    @Autowired
    private YgOrderLogService ygOrderLogService;
    @Autowired
    private FileService fileService;
    @Value("${micro.msg.appId}")
    private String appid;
    @Value("${wechat.pay.mchid}")
    private String mchid;
    @Value("${micro.msg.secret}")
    private String appsecret;
    @Value("${wechat.pay.notify_url}")
    private String notify_url;
    @Value("${wechat.pay.key}")
    private String key;
    @Autowired
    private YgWeChatService weChatService;
    @Autowired
    private YgRechargeMemberRecordService ygRechargeMemberRecordService;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private YgSkuService skuService;
    @Autowired
    private TrustoneService trustoneService;
    @Autowired
    private OrderPaySuccessObservable orderPaySuccessObservable;
    @Autowired
    private YgBmdismService ygBmdismService;

    private final SalesPlatform salesPlatform = SalesPlatform.Yiigoo;

    private final String DISABLE_COUPON_KEY = "disablecoupon";
    @Autowired
    private YgCustomsApi ygCustomsApi;
    @Autowired
    private ShoppingCarHandler shoppingCarHandler;
    @Autowired
    private CommitOrderHandler commitOrderHandler;

    /**
     * 跳转到结算页面
     *
     * @param skuIds
     * @param callback
     * @return
     */
    @RequestMapping(value = "toSettlementPage")
    @ResponseBody
    public JSONPObject toSettlementPage(Long[] skuIds, String callback) {
        JSONPObject json = null;
        YgUser user = SessionUtil.getCurrentUser();
        Message message = orderService.toSettlementPage(skuIds, user.getId());
        json = new JSONPObject(callback, message);
        return json;
    }

    /**
     * 获取商品数据
     *
     * @param callback
     * @return
     */
    @RequestMapping(value = "findItemInfo", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findItemInfo(@RequestParam(defaultValue = "false") Boolean distribution, String callback) {
        JSONPObject json = null;
        YgUser user = SessionUtil.getCurrentUser();
        Map<String, Object> map = new HashMap<String, Object>();
        List<YgShoppingCarModel> list = shoppingCarService.findIsCheck(user.getId(), distribution);

        //设置多买多折标记
        ygBmdismService.getBestBmdism(list);
        shoppingCarService.doNewCusBussness(list);
        List<List<YgShoppingCarModel>> sortCarList = shoppingCarService.sortCarList(list, user.getId());

        CarPackPriceResult disAndSpecialPrice = shoppingCarHandler.getPackAndNewCustomDisAndSpecialPrice(list);
        map.put("carList", sortCarList);
        map.put("productPrice", disAndSpecialPrice.getProductPrice());
        map.put("specialPrice", disAndSpecialPrice.getSpecialPrice());
        map.put("vipDisPrice", disAndSpecialPrice.getVipDisPrice());
        map.put("trustoneFlag", trustoneService.validateIsTrustonerOrder(list));
        json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
        return json;
    }

    /**
     * 删除订单
     *
     * @param orderId
     * @param callback
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject delete(Long orderId, String callback) {
        JSONPObject json = null;
        YgUser user = SessionUtil.getCurrentUser();
        int row = orderService.deleteSoft(orderId, user.getId());
        json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, row));
        return json;
    }

    /**
     * 确认收货
     *
     * @param orderId
     * @param callback
     * @return
     */
    @RequestMapping(value = "confirmReceipt", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject confirmReceipt(Long orderId, String callback) {
        JSONPObject json = null;
        YgUser user = SessionUtil.getCurrentUser();
        Message msg = orderService.confirmReceipt(orderId, user.getId());
        json = new JSONPObject(callback, msg);
        return json;
    }

    /**
     * 取消订单
     *
     * @param orderId
     * @param callback
     * @return
     */
    @RequestMapping(value = "cancelOrder", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject cancelOrder(Long orderId, String cancelReason, String callback) {
        JSONPObject json = null;
        YgUser user = SessionUtil.getCurrentUser();
        orderService.cancelOrder(orderId, user.getId(), user.getUserName(), cancelReason);
        Boolean isNewCustom = userService.isNewCustom(user.getId());

        // ygSalesPromotionService.removeCacheByAll(orderId,
        // user.getUserName());
        json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, isNewCustom));
        return json;
    }

    /**
     * 零元订单支付完成
     *
     * @param orderId
     * @param callback
     * @return
     */
    @RequestMapping(value = "completeZeroOrder", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject completeZeroOrder(Long orderId, String callback) {
        YgUser user = SessionUtil.getCurrentUser();
        YgOrder order = orderService.findByOrderId(orderId);
        if (order == null || order.getUserId().longValue() != user.getId().longValue() || order.getTotalPrice().compareTo(new BigDecimal("0.00")) != 0) {
            return new JSONPObject(callback, Message.error("订单编号有误或金额不符，请重试", null));
        }

        Long paymentCode = ygFrameCodeService.getFrameCode(CodeType.OrderPM, new Date());
        orderPaymentService.addPaymentRecord(orderId.toString(), zero, paymentCode.toString(), PayType.Account, AppType.WeChat);
        int i = orderService.splitOrderV2(orderId, new BigDecimal(0), PayType.Account);
        if (i == 0) {
            return new JSONPObject(callback, Message.error("订单金额有误请核对订单", null));
        }
        try {
            orderPaySuccessObservable.paySuccess(new OrderPayModel(orderId, BigDecimal.ZERO, PayType.Account, paymentCode.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, null));
    }

    /**
     * 提交订单
     *
     * @param userAddressId
     * @param couponDetailId
     * @param payType
     * @param totalPrice
     * @param formId
     * @param callback
     * @param sourceCode
     * @param accountPrice
     * @param userRemark
     * @param expressCardId  单次包邮卡id
     * @param request
     * @return
     */
    @RequestMapping(value = "commitOrder")
    @ResponseBody
    public JSONPObject commitOrder(OrderCommitParam commitParam) {
        commitParam.setSalesPlatform(SalesPlatform.Yiigoo);
        commitParam.setPlatformNo("M000");
        if (PayType.Small.equals(commitParam.getPayType())) {
            commitParam.setPayType(PayType.WeChat);
        }
        if (commitParam.getAppType() == null) {
            commitParam.setAppType(AppType.WeChat);
        }
        JSONPObject json = null;
        YgUser user = SessionUtil.getCurrentUser();
        commitParam.setUserId(user.getId());
        commitParam.setUserName(user.getUserName());
        String openid = user.getOpenId();
        if ("undefined".equals(commitParam.getSourceCode())) {
            commitParam.setSourceCode(null);
        }
        commitParam.setCouponDetailId(validateDisableCouponFromRedis(commitParam.getCouponDetailId()));
        commitParam.setSalesPlatform(SalesPlatform.Yiigoo);
        ygOrderLogService.addOrderLog(user.getId(), OrderStatus.WaitingPay, user.getUserName(), "提交订单,【入参】：" + JSON.toJSONString(commitParam));

        List<YgShoppingCarModel> carList = shoppingCarService.findIsCheck(user.getId(), commitParam.isDistribution());
        Message msg = commitOrderHandler.commitOrder(commitParam, carList);

        // 订单保存成功
        if (msg.getType().equals(Message.Type.success)) {
            Map<String, Object> map = (Map<String, Object>) msg.getExtra();
            map.put("openid", openid);
            map.put("totalPrice", commitParam.getTotalPrice().subtract(commitParam.getAccountPrice()));
            msg.setExtra(map);
            msg.setContent("订单提交成功");
            ygOrderLogService.addOrderLog((Long) map.get("orderId"), OrderStatus.WaitingPay, user.getUserName(), "订单提交成功：" + map.toString());
        } else {
            logger.error("订单提交失败，userId：" + user.getId() + ";msgType:" + msg.getType() + ";msg:" + msg.getContent() + ";msgExtra:" + (msg.getExtra() == null
                    ? "" : msg.getExtra().toString()));
        }

        return new JSONPObject(commitParam.getCallback(), msg);
    }

    /**
     * 验证优惠券禁用设置
     *
     * @return
     */
    @SuppressWarnings("rawtypes")
    private Long validateDisableCouponFromRedis(Long couponDetailId) {
        try {
            String couponInfo = redisDao.get(DISABLE_COUPON_KEY);
            Map map = JSON.parseObject(couponInfo, Map.class);
            if (MapUtils.isEmpty(map)) {
                return couponDetailId;
            }
            Long currentTime = new Date().getTime();
            String startDate = map.get("startDate").toString();
            String endDate = map.get("endDate").toString();
            String format = "yyyy-MM-dd HH:mm:ss";
            Long startTime = DateConvertUtils.parse(startDate + " 00:00:00", format).getTime();
            Long endTime = DateConvertUtils.parse(endDate + " 23:59:59", format).getTime();
            if (startTime.compareTo(currentTime) > 0 || endTime.compareTo(currentTime) < 0) {
                return couponDetailId;
            }
        } catch (Exception e) {
            logger.error("验证优惠券禁用设置异常，" + ExceptionUtil.getExceptionMsg(e));
            return couponDetailId;
        }
        return null;
    }

    /**
     * 微信统一下单
     *
     * @param userIp
     * @param code
     * @param state
     * @param callback
     * @param model
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "UnifiedOrderJSAPI")
    @ResponseBody
    public JSONPObject UnifiedOrderJSAPI(String code, String state, String callback, Model model, HttpServletRequest request) throws IOException {

        YgUser user = SessionUtil.getCurrentUser();
        JSONPObject json = null;
        Message msg = null;
        String openid = null;
        String ipAddress = WebUtils.getIpAddr(request);
        String[] split = ipAddress.split(",");
        ipAddress = split[0];
        String[] str = state.split("-");
        PayRequest payRequest = null;
        // 记录入参日志
        ygOrderLogService.addOrderLog(Long.parseLong(str[0]), OrderStatus.WaitingPay, user.getUserName(), "微信支付：入参【code：" + code + ";state：" + state + "】");
        // 判断该订单是否已经支付过
        YgOrder ygOrder = orderService.findByOrderId(Long.parseLong(str[0]));
        if (ygOrder != null && !ygOrder.getOrderStatus().equals(OrderStatus.WaitingPay)) {
            return new JSONPObject(callback, Message.success(true));
        }
        try {
            if (StringUtils.isNotEmpty(code)) {
                OauthToken oauthToken = wxMpAuthorityService.findOauthToken(code);
                openid = oauthToken.getOpenId();
                userService.bindingOpenId(user.getId(), openid, null, oauthToken.getUnionId());
                ygOrderLogService.addOrderLog(Long.parseLong(str[0]), OrderStatus.WaitingPay, user.getUserName(), "微信支付，发起微信授权获取openId，openId=" + openid);
            } else {
                if (user.getOpenId() == null) {
                    user = userService.findById(user.getId());
                }
                openid = user.getOpenId();
            }

            // 生成支付流水
            Long paymentCode = ygFrameCodeService.getFrameCode(CodeType.OrderPM, new Date());
            System.out.println(appid + "====" + mchid + "=========" + openid);
            System.out.println(appid + "====" + mchid + "=========" + openid);
            UnifiedOrderReqData reqData = new UnifiedOrderReqData.UnifiedOrderReqDataBuilder(appid, mchid, "壹果订单", paymentCode.toString(), new BigDecimal
                    (str[1]).multiply(new BigDecimal(100)).intValue(), ipAddress, notify_url, TradeType.JSAPI.name()).setOpenid(openid).build();
            msg = weChatService.UnifiedOrderJSAPI(reqData);
            if (msg.getType().equals(Message.Type.error)) {
                return new JSONPObject(callback, Message.error(documentConstant.MESSAGE_ERROR, msg));
            }
            payRequest = (PayRequest) msg.getExtra();
            payRequest.setPartnerId(paymentCode.toString());
            orderPaymentService.addPaymentRecord(BusinessModule.Order, str[0], new BigDecimal(str[1]), paymentCode.toString(), PayType.WeChat, AppType
                    .WeChat, payRequest.getPrepayId(), null, null);
        } catch (Exception e) {
            ygOrderLogService.addOrderLog(Long.parseLong(str[0]), OrderStatus.WaitingPay, user.getUserName(), "JSAPI;发起微信支付失败" + e.getMessage());
            e.printStackTrace();
            return new JSONPObject(callback, Message.error(documentConstant.MESSAGE_ERROR, null));
        }
        json = new JSONPObject(callback, Message.success(payRequest));
        return json;
    }

    /**
     * 微信统一下单
     *
     * @param userIp
     * @param code
     * @param state
     * @param callback
     * @param model
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "UnifiedOrderNATIVE")
    @ResponseBody
    public JSONPObject UnifiedOrderNATIVE(String state, String callback, Model model, HttpServletRequest request) throws IOException {

        YgUser user = SessionUtil.getCurrentUser();
        JSONPObject json = null;
        Message msg = null;
        String ipAddress = WebUtils.getIpAddr(request);
        System.out.println("客户端ip：" + ipAddress);
        String[] split = ipAddress.split(",");
        ipAddress = split[0];
        System.out.println("客户端ip：" + ipAddress);
        System.out.println("微信支付回调地址：" + notify_url);
        String[] str = state.split("-");
        String coderUrl = "";
        // 判断该订单是否已经支付过
        YgOrder ygOrder = orderService.findByOrderId(Long.parseLong(str[0]));
        if (ygOrder != null && !ygOrder.getOrderStatus().equals(OrderStatus.WaitingPay)) {
            return new JSONPObject(callback, Message.success(true));
        }

        try {
            // 生成支付流水
            Long paymentCode = ygFrameCodeService.getFrameCode(CodeType.OrderPM, new Date());

            UnifiedOrderReqData reqData = new UnifiedOrderReqData.UnifiedOrderReqDataBuilder(appid, mchid, "壹果订单", paymentCode.toString(), new BigDecimal
                    (str[1]).multiply(new BigDecimal(100)).intValue(), ipAddress, notify_url, TradeType.NATIVE.name()).setProduct_id("000").build();
            msg = weChatService.UnifiedOrderNATIVE(reqData);
            if (msg.getType().equals(Message.Type.error)) {
                return new JSONPObject(callback, Message.error(documentConstant.MESSAGE_ERROR, msg));
            }
            coderUrl = (String) msg.getExtra();
            coderUrl = this.getPayCode(coderUrl, paymentCode, request);
            orderPaymentService.addPaymentRecord(BusinessModule.Order, str[0], new BigDecimal(str[1]), paymentCode.toString(), PayType.WeChat, AppType
                    .WeChat, null, null, null);
        } catch (Exception e) {
            ygOrderLogService.addOrderLog(Long.parseLong(str[0]), OrderStatus.WaitingPay, user.getUserName(), "NATIVE；发起微信支付失败" + e.getMessage());
            e.printStackTrace();
            return new JSONPObject(callback, Message.error(documentConstant.MESSAGE_ERROR, null));
        }
        json = new JSONPObject(callback, Message.success(coderUrl));
        return json;
    }

    /**
     * 查询订单是否支付成功
     *
     * @param payOrderCode
     * @param orderId
     * @param orderPrice
     * @param callback
     * @return
     */
    @RequestMapping(value = "isPaySuccess")
    @ResponseBody
    public JSONPObject isPaySuccess(Long orderId, String callback) {
        YgOrder order = orderService.findByOrderId(orderId);
        List<OrderStatus> orderStautss = new ArrayList<OrderStatus>();
        orderStautss.add(OrderStatus.TradeClosed);
        orderStautss.add(OrderStatus.WaitingPay);
        if (!orderStautss.contains(order.getOrderStatus())) {
            return new JSONPObject(callback, Message.success(true));
        } else {
            return new JSONPObject(callback, Message.success(false));

        }
    }

    /**
     * 微信统一下单回调
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "unifiedOrderCallBack")
    public void unifiedOrderCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        ServletInputStream in = request.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        String result = new String(out.toByteArray(), "UTF-8");
        ygOrderLogService.addOrderLog(1l, OrderStatus.WaitingSend, "系统", "微信支付回调，回调数据 【" + result + "】;");

        String res = weChatService.UnifiedOrderCallBack(result);

        ygOrderLogService.addOrderLog(1l, OrderStatus.WaitingSend, "系统", "微信支付回调，返回微信数据 【" + res + "】;");
        logger.debug("\n微信支付回调返回结果：\n" + res);
        out.close();
        in.close();
        response.getWriter().print(res);
    }

    private String getPayCode(String coderUrl, Long paymentCode, HttpServletRequest request) {
        String path = request.getRealPath("/");
        String realPath = path + "/PayCodeImage";
        String fileName = "payCode" + paymentCode + ".jpg";
        String qrcodeUrl = "";
        try {
            realPath = QRCodeUtil.encode(coderUrl, realPath, fileName);
            if (!StringUtil.isBlank(realPath)) {
                File file = new File(realPath);
                String ext = fileName.split("\\.")[1];
                qrcodeUrl = fileService.uploadImage(file, new FileType[]{FileType.PayCode}, ext, true, request);

            }
        } catch (Exception e) {
            logger.error("生成微信扫码支付二维码失败。paymentCode=" + paymentCode);
            e.printStackTrace();
        }
        return qrcodeUrl;

    }

    public static boolean GenerateImage(String imgStr, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null || null == imgFilePath) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b, 0, b.length);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @RequestMapping(value = "saveMemberOrder")
    @ResponseBody
    public JSONPObject saveMemberOrder(String addrInfo, String skuIds, Date birthday, Integer gender, String callback) {
        YgUser user = SessionUtil.getCurrentUser();

        YgUser ygUser = new YgUser();
        ygUser.setId(user.getId());
        ygUser.setBabyBirthday(birthday);
        ygUser.setGender(gender);
        userService.updateUserInfo(ygUser);

        YgUserAddress address = JSON.parseObject(addrInfo, new TypeReference<YgUserAddress>() {
        });
        Long paymentCode = ygFrameCodeService.getFrameCode(CodeType.RechargeMB, new Date());

        Message message = ygRechargeMemberRecordService.saveMemberOrder(user, paymentCode, address, skuIds);
        if (message.equals(Message.Type.error)) {
            return new JSONPObject(callback, message);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("paymentCode", paymentCode);
        map.put("openId", user.getOpenId());
        return new JSONPObject(callback, Message.success(map));
    }

    /**
     * 商品信息（立即购买）
     *
     * @param callback
     * @param skuInfos
     * @return
     */
    @RequestMapping(value = "findItemInfoForPayNow", method = RequestMethod.GET)
    public String findItemInfoForPayNow(String callback, String skuInfos) {
        return skuService.checkSkuInfoIsGroup(skuInfos) ? "forward:/mobile/grouporder/findItemInfoPt.do" : "forward:/mobile/order/findItemInfoWithSkuInfo.do";
    }

    @RequestMapping(value = "findItemInfoWithSkuInfo", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findItemInfoWithSkuInfo(@RequestParam(defaultValue = "false") Boolean distribution, String callback, String skuInfos) {
        JSONPObject json = null;
        YgUser user = SessionUtil.getCurrentUser();
        Map<String, Object> map = new HashMap<String, Object>();
        List<BaseSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<BaseSkuInfo>>() {
        });
        List<YgShoppingCarModel> list = shoppingCarService.findItemInfo(skuList, user.getId(), PromotionType.Ordinary, distribution);
        List<List<YgShoppingCarModel>> sortCarList = shoppingCarService.sortCarListV2(list, user.getId());
        Map<String, BigDecimal> priceMap = orderService.getProductPrice(list);
        map.put("carList", sortCarList);
        map.put("productPrice", priceMap.get("productPrice"));
        map.put("specialPrice", priceMap.get("specialPrice"));
        map.put("vipDisPrice", priceMap.get("vipDisPrice"));
        map.put("trustoneFlag", trustoneService.validateIsTrustonerOrder(list));
        json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
        return json;
    }

    /**
     * 提交订单（立即购买）
     *
     * @param userAddressId
     * @param couponDetailId
     * @param payType
     * @param totalPrice
     * @param formId
     * @param callback
     * @param sourceCode
     * @param accountPrice
     * @param userRemark
     * @param expressCardId
     * @param request
     * @param orderType
     * @param skuInfos
     * @return
     */
    @RequestMapping(value = "commitOrderForPayNow")
    public String commitOrderForPayNow(CommitOrderRequestParam orderRequestParam, HttpServletRequest request) {
        orderRequestParam.setOrderType(orderRequestParam.getOrderType() == null ? OrderType.CardCoupon : orderRequestParam.getOrderType());
        orderRequestParam.setUserAddressId(orderRequestParam.getUserAddressId() == null ? -1L : orderRequestParam.getUserAddressId());
        request.setAttribute("sourceOrderType", orderRequestParam.getOrderType().name());
        return skuService.checkSkuInfoIsGroup(orderRequestParam.getSkuInfos()) ? "forward:/mobile/grouporder/commitOrderPt.do" :
                "forward:/mobile/order/commitOrderWithSkuInfo.do";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "commitOrderWithSkuInfo")
    @ResponseBody
    public JSONPObject commitOrderWithSkuInfo(CommitOrderRequestParam orderRequestParam) {
        YgUser user = SessionUtil.getCurrentUser();
        String openid = user.getOpenId();

        PayType payType = orderRequestParam.getPayType();
        if (PayType.Small.equals(payType)) {
            payType = PayType.WeChat;
        }

        Long couponDetailId = validateDisableCouponFromRedis(orderRequestParam.getCouponDetailId());

        Message msg = null;
        ygOrderLogService.addOrderLog(user.getId(), OrderStatus.WaitingPay, user.getUserName(), "提交订单,【入参】：" + orderRequestParam.toString());

        List<YgShoppingCarModel> list = shoppingCarService.findItemInfo(orderRequestParam.getSkuList(), user.getId(), PromotionType.Ordinary, orderRequestParam.getDistribution());

        // 保存订单
        msg = orderService.commitOrder(user.getId(), user.getUserName(), orderRequestParam.getUserAddressId(), couponDetailId, orderRequestParam
                        .getTotalPrice(), orderRequestParam.getAppType(), payType, orderRequestParam.getSourceCode(), orderRequestParam.getAccountPrice(),
                orderRequestParam.getFormId(), orderRequestParam.getUserRemark(), orderRequestParam.getExpressCardId(), orderRequestParam.getOrderType(),
                list, orderRequestParam.getPlatformNo(), orderRequestParam.getIdentityNo(), salesPlatform);

        // 订单保存成功
        if (msg.getType().equals(Message.Type.success)) {
            Map<String, Object> map = (Map<String, Object>) msg.getExtra();
            map.put("openid", openid);
            map.put("totalPrice", orderRequestParam.getTotalPrice().subtract(orderRequestParam.getAccountPrice()));
            msg.setExtra(map);
            msg.setContent("订单提交成功");
            ygOrderLogService.addOrderLog((Long) map.get("orderId"), OrderStatus.WaitingPay, user.getUserName(), "订单提交成功：" + map.toString());
        } else {
            logger.error("订单提交失败，userId：" + user.getId() + ";msgType:" + msg.getType() + ";msg:" + msg.getContent() + ";msgExtra:" + (msg.getExtra() == null
                    ? "" : msg.getExtra().toString()));
        }
        return new JSONPObject(orderRequestParam.getCallback(), msg);
    }

    @RequestMapping(value = "queryCustoms", method = RequestMethod.GET)
    @ResponseBody
    public Object queryCustoms(Long orderId) throws YgHttpException {
        return ygCustomsApi.queryCustoms(orderId);
    }

    @RequestMapping(value = "pushTrustonerOrderAndDeclareCustoms", method = RequestMethod.GET)
    @ResponseBody
    public String pushTrustonerOrderAndDeclareCustoms(Long orderId) {
        trustoneService.pushTrustonerOrderAndDeclareCustoms(orderId);
        return "";
    }

    @RequestMapping(value = "cancelTrustoneOrder", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult cancelTrustoneOrder(String orderId) throws YgHttpException {
        return trustoneService.cancelorder(orderId, "");
    }

}
